package com.xinyi.smart_translator.audioservice

import android.Manifest
import android.app.Notification
import android.app.Service
import android.content.Intent
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.os.IBinder
import androidx.annotation.RequiresPermission
import androidx.core.app.NotificationCompat
import com.xinyi.smart_translator.R
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel

class AudioStreamService : Service(), EventChannel.StreamHandler, MethodChannel.MethodCallHandler {

    private var audioRecord: AudioRecord? = null
    private var isRecording = false
    private var eventSink: EventChannel.EventSink? = null
    private val bufferSize = AudioRecord.getMinBufferSize(
        44100,
        AudioFormat.CHANNEL_IN_MONO,
        AudioFormat.ENCODING_PCM_16BIT
    )

    // Flutter MethodChannel（用于控制录音）
    private lateinit var methodChannel: MethodChannel

    val NOTIFICATION_ID: Int = 1
    val CHANNEL_ID: String = "AudioRecordingChannel"


    override fun onCreate() {
        super.onCreate()
        val flutterEngine = FlutterEngine(this)

        // EventChannel（发送音频数据）
        EventChannel(flutterEngine.dartExecutor, "com.example.audio_stream")
            .setStreamHandler(this)

        // MethodChannel（接收 Flutter 控制指令）
        methodChannel = MethodChannel(flutterEngine.dartExecutor, "com.example.audio_control")
        methodChannel.setMethodCallHandler(this)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
         return START_STICKY
    }

    // 处理 Flutter 的方法调用（startRecording / stopRecording）
    @RequiresPermission(Manifest.permission.RECORD_AUDIO)
    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        when (call.method) {
            "startRecording" -> {
                if (!isRecording) startStreaming()
                result.success(null)
            }
            "stopRecording" -> {
                if (isRecording) stopStreaming()
                result.success(null)
            }
            else -> result.notImplemented()
        }
    }

    // EventChannel 监听（Flutter 开始接收数据）
    override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
        eventSink = events
    }

    override fun onCancel(arguments: Any?) {
        eventSink = null
    }

    // 开始录音并发送数据到 Flutter
    @RequiresPermission(Manifest.permission.RECORD_AUDIO)
    private fun startStreaming() {
        isRecording = true
        audioRecord = AudioRecord(
            MediaRecorder.AudioSource.MIC,
            44100,
            AudioFormat.CHANNEL_IN_MONO,
            AudioFormat.ENCODING_PCM_16BIT,
            bufferSize
        )

        val notification: Notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Audio Recorder")
            .setContentText("Recording in progress")
            .setSmallIcon(R.drawable.ic_launcher)
            .build()

        startForeground(NOTIFICATION_ID, notification)

        Thread {
            audioRecord?.startRecording()
            val buffer = ByteArray(bufferSize)

            while (isRecording) {
                val bytesRead = audioRecord?.read(buffer, 0, bufferSize) ?: -1
                if (bytesRead > 0) {
                    eventSink?.success(buffer) // 发送 PCM 数据到 Flutter
                }
            }

            audioRecord?.stop()
            audioRecord?.release()
        }.start()
    }

    // 停止录音
    private fun stopStreaming() {
        isRecording = false
    }

    override fun onBind(intent: Intent?): IBinder? = null

}